package com.mgr.controller;

import java.util.List;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.mgr.model.Accounts;
import com.mgr.model.Transactions;
import com.mgr.service.AccountService;

@Controller
public class ExternalTransferController1 {

	@Autowired
	private AccountService accountService;

	private ResourceBundle rb = ResourceBundle
			.getBundle("com.mgr.messages.errorMessage");

	@RequestMapping("externalTransfer1")
	public ModelAndView processexternalTransfer1(HttpSession session) {
		ModelAndView modeView = new ModelAndView();
		String id = (String) session.getAttribute("user");
		if (id == null || id == "") {
			modeView.setViewName("login");
		} else {
			List<Accounts> lstAcc = accountService.getAccountByCustId(Integer
					.parseInt(id));
			if (lstAcc.isEmpty()) {
				modeView.addObject("err", rb.getObject("accEmpty"));
				modeView.setViewName("welcome.tile");
			} else {
				modeView.addObject("listAccId",
						accountService.getAccountByCustId(Integer.parseInt(id)));
				if (session.getAttribute("trans") != null) {
					modeView.addObject("trans", session.getAttribute("trans"));
				}
				modeView.setViewName("externalTransfer1.tile");
			}
		}
		return modeView;
	}

	@RequestMapping("ExternalTrans1")
	public ModelAndView doAction1(HttpServletRequest request,
			HttpSession session) {
		ModelAndView modeView = new ModelAndView();
		String id = (String) session.getAttribute("user");
		if (id == null || id == "") {
			modeView.setViewName("login");
		} else {
			int accountSender = Integer.parseInt(request
					.getParameter("account"));
			int amountOfMoney = Integer
					.parseInt(request.getParameter("amount"));
			Transactions trans = new Transactions();
			trans.setAccId1(accountSender);
			trans.setAccId2(Integer.parseInt(request
					.getParameter("accountRecieve")));
			trans.setAmount(amountOfMoney);
			session.setAttribute("trans", trans);
			if (!accountService.verifyBalance(accountSender, amountOfMoney)) {
				int custId = Integer.parseInt((String) session
						.getAttribute("user"));
				modeView.addObject("listAccId",
						accountService.getAccountByCustId(custId));
				modeView.addObject("err", rb.getObject("errAmount"));
				modeView.setViewName("externalTransfer1.tile");
			} else {
				session.setAttribute("step1", true);
				modeView.setViewName("redirect:externalTransfer2");
				session.setAttribute("balance",
						accountService.getAccount(accountSender).getBalance());
			}
		}
		return modeView;
	}
}
